﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using WebApiV4Test.Interface.Log;
using WebApiV4Test.Utils.Log;

namespace WebApiV4Test.Utils.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILog _log;
        public GlobalExceptionFilter(ILog log)
        {
            _log = log;
        }
        public void OnException(ExceptionContext context)
        {
            _log.Error(context.Exception);
            var json = new ErrorResponse("未知错误,请重试");
            context.Result = new ApplicationErrorResult(json);
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.ExceptionHandled = true;
        }
        /// <summary>
        /// 
        /// </summary>
        public class ApplicationErrorResult : ObjectResult
        {
            public ApplicationErrorResult(object value) : base(value)
            {
                StatusCode = (int)HttpStatusCode.InternalServerError;
            }
        }

        public class ErrorResponse
        {
            public ErrorResponse(string msg)
            {
                Message = msg;
            }
            public string Message { get; set; }
            public object DeveloperMessage { get; set; }
        }
    }
}
